package com.boesch.electroOffice.presentation.appointment;

import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;

import org.springframework.stereotype.Controller;

import com.boesch.electroOffice.utils.ArrayListUtils;
import com.boesch.electroOffice.utils.ConfigurationUtils;
import com.boesch.electroOffice.utils.MessageUtils;
import com.boesch.electroOffice.utils.PortletUtils;
import com.boesch.electroOffice.utils.RoleUtils;
import com.liferay.portal.model.Role;

/**
 * This class is used to manage the configuration of appointmentPortlet
 * 
 * @author Ralph Koster
 *
 */
@ManagedBean
@SessionScoped
@Controller
public class AppointmentConfigurationController implements Serializable {
	
	private static final long serialVersionUID = 7332817862966780306L;
	
	private Map<String, String> roles;
	private Map<String, String> subfunctions;
	private Map<String, Map<String, Boolean>> roleSubfunctions;
	
	public void init() {
		roles = new LinkedHashMap<String, String>();
		List<Role> lrRoles = RoleUtils.getAllBoeschRoles();
		for(Role role : lrRoles) {
			roles.put(role.getName(), role.getName());
		}
		
		subfunctions = new LinkedHashMap<String, String>();
		List<String> subfAppNav = ArrayListUtils.addStringArraysToArrayList(AppointmentSubfunctionUtils.getSubfunctionArrays());
		for(String subfunction : subfAppNav) {
			subfunctions.put(subfunction, subfunction);
		}
		
		roleSubfunctions = new HashMap<String, Map<String, Boolean>>();
	    for (String role : roles.keySet()) {
	    	Map<String, Boolean> roleSubf = new HashMap<String, Boolean>();
	    	for(String subfunction : subfAppNav) {
				roleSubf.put(subfunction, ConfigurationUtils.getRoleSubfunctionPreference(role, subfunction));
			}
	    	roleSubfunctions.put(role, roleSubf);
	    }
	}

	public void submit(ActionEvent event) {
	    for (Entry<String, Map<String, Boolean>> entry : roleSubfunctions.entrySet()) {
	        String role = entry.getKey();
	        Map<String, Boolean> subfunctions = entry.getValue();
	        String checkedSubfunctions = "";
	        for(Entry<String, Boolean> subfunction : subfunctions.entrySet()) {
	        	if(subfunction.getValue()) {
	        		checkedSubfunctions += subfunction.getKey() + ",";
	        	}
	        }
	        PortletUtils.setPortletPreference(role + "Permissions", checkedSubfunctions);
	        MessageUtils.addInfoMessage("Einstellungen erfolgreich gespeichert!");
	    }
	}

	public Map<String, String> getRoles() {
		return roles;
	}
	
	public Map<String, String> getSubfunctions() {
		return subfunctions;
	}
	
	public Map<String, Map<String, Boolean>> getRoleSubfunctions() {
		return roleSubfunctions;
	}
}
